/*
 * Copyright (c) YouYuan 2018. https://gitee.com/you-yuan
 */

package com.yuan.crawler.proxy.impl;

import com.yuan.crawler.proxy.IPProxy;
import com.yuan.crawler.proxy.ProxyApi;
import com.yuan.crawler.proxy.ProxyServer;
import com.yuan.util.collection.ListUtil;
import com.yuan.util.date.DateUtil;
import com.yuan.util.number.NumUtil;
import com.yuan.util.string.StrUtil;
import com.yuan.util.web.HttpUtil;

import java.util.*;
import java.util.regex.Matcher;

/**
 * 芝麻代理服务类
 * @author YouYuan
 * @version 1.0
 * @CreateDate 2018/7/12 15:51
 * @UpdateDate 2018/7/12 15:51
 */
public class ZMProxyServerImpl implements ProxyServer {

    private static final List<ProxyApi> ZM_API_LIST = new ArrayList<ProxyApi>();

    private Double balance;
    private Date balanceDate;

    static {
        ProxyApi free = new ProxyApi();
        free.setApiUrl("http://webapi.http.zhimacangku.com/getip?num=20&type=1&pro=&city=0&yys=0&port=1&pack=18369");
        free.setDisableTime(60);//免费额度每次获取失败禁用60分钟
        ProxyApi charge = new ProxyApi();
        charge.setApiUrl("http://webapi.http.zhimacangku.com/getip?num=20&type=1&pro=&city=0&yys=0&port=1&time=1&ts=1&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1");
        charge.setDisableTime(1);//收费额度每次禁用1分钟
        ZM_API_LIST.add(free);
        ZM_API_LIST.add(charge);
    }

    @Override
    public List<IPProxy> requestNewProxy() {
        for (int i = 0; i < ZM_API_LIST.size(); i++) {
            ProxyApi proxyApi = ZM_API_LIST.get(i);
            if (proxyApi == null) {
                ZM_API_LIST.remove(proxyApi);
                continue;
            }
            /**
             * 如果api不可用并且重新启用时间大于当前时间，则跳过该API的调用
             */
            if (!proxyApi.isUsable() && DateUtil.compareNow(proxyApi.getReactivateTime()) >= 0) {
                continue;
            } else {
                proxyApi.enable();
            }
            String apiUrl = proxyApi.getApiUrl();
            List<IPProxy> ipList = processApiData(apiUrl);
            if (ListUtil.isEmpty(ipList)) {
                proxyApi.disable();
            } else {
                Collections.sort(ipList);
                if (ipList.size() >= 2) {
                    /**
                     * 只取过期时间最长的两个IP
                     */
                    List<IPProxy> rsList = new ArrayList<IPProxy>(2);
                    rsList.add(ipList.get(0));
                    rsList.add(ipList.get(1));
                    return rsList;
                } else {
                    return ipList;
                }
            }
        }
        return null;
    }

    @Override
    public Double requestBalance() {
        return null;
    }

    private List<IPProxy> processApiData(String apiUrl) {
        List<IPProxy> ipList = new ArrayList<IPProxy>(20);
        String json = null;
        try {
            json = HttpUtil.httpGet(apiUrl);
            if (StrUtil.notEmpty(json)) {
                Matcher matcher = ProxyServer.IP_PORT_PATTERN.matcher(json);
                if (matcher.find()) {
                    do {
                        String ipAndPort = matcher.group();
                        String[] split = ipAndPort.split(":");
                        IPProxy ipProxy = new IPProxy();
                        ipProxy.setIp(split[0]);
                        ipProxy.setPort(NumUtil.toInt(split[1]));
                        Calendar instance = Calendar.getInstance();
                        instance.add(Calendar.MINUTE, 10);
                        ipProxy.setExpires(instance.getTime());
                        ipList.add(ipProxy);
                    } while (matcher.find());
                }
            }
        } catch (Exception e) {
        }
        return ipList;
    }

    @Override
    public String toString() {
        return "ZMProxyServerImpl:" + this.hashCode();
    }
}
